<?php

namespace app\order\logic;

use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

class OrderValidityLogic extends BasicLogic
{
    public function __construct()
    {
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $limit            = $params['limit'] ?? 10;
        $order_id         = $params['order_id'] ?? 0;
        $shop_id          = $params['shop_id'] ?? 0;
        $OrderTime      = $params['OrderTime'] ?? "";
        $DeliveryTime      = $params['DeliveryTime'] ?? "";
        $track_number     = $params['tracking_number'] ?? "";
        $track_status     = $params['payout_status'] ?? "ALL";
        $AbnormalState     = $params['AbnormalState'] ?? "ALL";
        $provider_name    = $params['provider_name'] ?? "";
        $platform_track   = $params['platform_track'] ?? "";
        $where            = [];

        if (!empty($OrderTime)){
            $where[] = ['OrderTime', '>=', $OrderTime['0']];
            $where[] = ['OrderTime', '<=', $OrderTime['1']];
        }else{
            $where[] = ['OrderTime', '>', 0];
        }
        if (!empty($DeliveryTime)){
            $where[] = ['DeliveryTime', '>=', $DeliveryTime['0']];
            $where[] = ['DeliveryTime', '<=', $DeliveryTime['1']];
        }

        if (!empty($track_status)){
            if ($track_status !== "ALL"){
                $where[] = ['latest_status', '=', $track_status];
            }
        }
        if (!empty($AbnormalState)){
            if ($AbnormalState !== "ALL"){
                $where[] = ['AbnormalState', '=', $AbnormalState];
            }
        }

        if (!empty($provider_name)){
            $where[] = ['provider_name', '=', $provider_name];
        }

        if (!empty($track_number)){
            $where[] = ['track_number', '=', $track_number];
        }

        if($platform_track=="0" || $platform_track>0){
            $where[] = ['platform_track', '=', $platform_track];
        }
        
        if(!empty($shop_id)){
            $where[] = ['shop_id', '=', $shop_id];
        }

        if(!empty($order_id)){
            $where[] = ['order_id','like', '%'.$order_id.'%'];
        }
        $where[] = ['update_time', '>=', "2025-08-09"];
        $where[] = ['platform_track', '=', 1];
        
        // halt($where);
        $list = Db::name('order_track')
            ->where($where)
            ->order('latest_time desc')
            ->paginate($limit);
        
        $lists = $list->items();
        foreach ($lists as $k=>$v) {
            if($v['tracking_list']){
                $tracking_list = json_decode($v['tracking_list'],true);
                if(is_array($tracking_list)){
                    $time_raw = $tracking_list[0]['time_raw'] ?? "";
                    $description = $tracking_list[0]['description'] ?? "";
                    // 时间 + 描述 增加回车
                    $time_raw_msg = $time_raw ."\n". $description;
                }
            }
            $lists[$k]['time_raw'] = $time_raw_msg ?? "";
        }
        
        //统计
        $spends = Db::name('order_track')
            ->field('COUNT(id) as spend,AbnormalState')
            ->group('AbnormalState')
            ->order('spend desc')
            ->where($where)
            ->select()->toarray();
            
        $spends_Total = 0;
        foreach ($spends as $k=>$v) {
            $spends_Total += (float)$v['spend'];
            switch ($v['AbnormalState']) {
                case '0':
                    $spends[$k]['platform'] = '无异常';
                    break;
                case '1':
                    $spends[$k]['platform'] = '超时未上网';
                    break;
                case '2':
                    $spends[$k]['platform'] = '物流断更';
                    break;
                case '3':
                    $spends[$k]['platform'] = '包裹退回';
                    break;
                case '4':
                    $spends[$k]['platform'] = '投递失败';
                    break;
                default:
                    $spends[$k]['platform'] = '未 知';
            }
        }
        
        $data = [
            'list' => $lists,
            'total' => $list->total(),
            'spends' => $spends,
            'spends_Total' => (int)$spends_Total,
        ];

        return json(DefaultResponse(200, true, '获取成功', $data));
    }
    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['订单编号', 'order_number'];
        $header[] = ['物流单号', 'track_number'];
        $header[] = ['最新物流状态', 'latest_status'];
        $header[] = ['上网(天)', 'SurfInternet'];
        $header[] = ['国内运输(天)', 'Domestic'];
        $header[] = ['承运(天)', 'AcceptCarriage'];
        $header[] = ['国外运输(天)', 'Foreign'];
        $header[] = ['签收(天)', 'SignFor'];
        $header[] = ['下单时间', 'OrderTime'];
        $header[] = ['发货时间', 'DeliveryTime'];
        $header[] = ['最后轨迹', 'time_raw'];
        $header[] = ['最后更新时间', 'latest_time'];
        $header[] = ['妥投时间', 'DeliveredTime'];
        $header[] = ['订单号', 'order_id'];

        $tableName = "Ordertrack";

        
        $order_id         = $params['order_id'] ?? 0;
        $shop_id          = $params['shop_id'] ?? 0;
        $OrderTime      = $params['OrderTime'] ?? "";
        $DeliveryTime      = $params['DeliveryTime'] ?? "";
        $track_number     = $params['tracking_number'] ?? "";
        $track_status     = $params['payout_status'] ?? "ALL";
        $AbnormalState     = $params['AbnormalState'] ?? "ALL";
        $provider_name    = $params['provider_name'] ?? "";
        $platform_track   = $params['platform_track'] ?? "";
        $where            = [];

        if (!empty($OrderTime)){
            $where[] = ['OrderTime', '>=', $OrderTime['0']];
            $where[] = ['OrderTime', '<=', $OrderTime['1']];
        }else{
            $where[] = ['OrderTime', '>', 0];
        }
        if (!empty($DeliveryTime)){
            $where[] = ['DeliveryTime', '>=', $DeliveryTime['0']];
            $where[] = ['DeliveryTime', '<=', $DeliveryTime['1']];
        }

        if (!empty($track_status)){
            if ($track_status !== "ALL"){
                $where[] = ['latest_status', '=', $track_status];
            }
        }
        if (!empty($AbnormalState)){
            if ($AbnormalState !== "ALL"){
                $where[] = ['AbnormalState', '=', $AbnormalState];
            }
        }

        if (!empty($provider_name)){
            $where[] = ['provider_name', '=', $provider_name];
        }

        if (!empty($track_number)){
            $where[] = ['track_number', '=', $track_number];
        }

        if($platform_track=="0" || $platform_track>0){
            $where[] = ['platform_track', '=', $platform_track];
        }
        
        if(!empty($shop_id)){
            $where[] = ['shop_id', '=', $shop_id];
        }

        if(!empty($order_id)){
            $where[] = ['order_id','like', '%'.$order_id.'%'];
        }
        $where[] = ['update_time', '>=', "2025-08-09"];
        $where[] = ['platform_track', '=', 1];
        
        // halt($where);
        $lists = Db::name('order_track')
            ->where($where)
            ->order('latest_time desc')
            ->select()->toarray();
        
        foreach ($lists as $k=>$v) {
            if($v['tracking_list']){
                $tracking_list = json_decode($v['tracking_list'],true);
                if(is_array($tracking_list)){
                    $time_raw = $tracking_list[0]['time_raw'] ?? "";
                    $description = $tracking_list[0]['description'] ?? "";
                    // 时间 + 描述 增加回车
                    $time_raw_msg = $time_raw ."\n". $description;
                }
            }
            $lists[$k]['time_raw'] = $time_raw_msg ?? "";
        }
            

        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    /**
    * @desc    物流轨迹信息
    * @date    2024/12/23
    * @author  zhangheng
    */
    public function trackinfo($params = [])
    {
        $track_number = $params['track_number'] ?? '';
        if(empty($track_number)){
            return json(DefaultResponse(400, false, '物流单号不能为空'));
        }
        //传订单号 查询物流轨迹以及订单信息
        $data = $this->TrackQuery($track_number);
        return $this->jsonMessage(200, true, '获取成功', $data);
    }

    /**
     * @desc    获取物流状态信息
     * @date    2024/12/29
     * @author  zhangheng
     */
    public function get_track_status(){
        $size_type   = Config('Logisticskey.track_info.status');
        $info        = getLevel($size_type);
        $arr[] = [
            'value'      => "ALL",
            'label'      => "所有",
        ];
        foreach($info as $v){
            $arr[] = [
                'value'      => $v['key'],
                'label'      => $v['value'],
            ];
        }
        return  $this->jsonMessage(200,true,'获取成功!',$arr);
    }


    /**
     * @desc    获取物流状态信息
     * @date    2024/12/29
     * @author  zhangheng
     */
    public function get_sub_status($params){
        $platform_track = $params['platform_track']??'0';
        if($platform_track =='1'){
            $size_type   = Config('Logisticskey.718_info.sub_status');
        }elseif($platform_track =='2'){
            $size_type   = Config('Logisticskey.4px_track.sub_status');
        }else{
            $size_type   = Config('Logisticskey.track_info.sub_status');
        }

        $info        = getLevel($size_type);
        foreach($info as $v){
            $arr[] = [
                'value'      => $v['key'],
                'label'      => $v['value'],
            ];
        }
        return  $this->jsonMessage(200,true,'获取成功!',$arr);
    }










    /**
    * @desc    物流轨迹信息
    * @date    2024/12/24
    * @author  zhangheng
    */
    public function TrackQuery($track_number)
    {
        $where[] = ['track_number', '=', $track_number];
        $info = Db::name('order_track')
            ->field('*')
            ->where($where)
            ->find();
        $info['receive_country'] = $info['receive_country']??'US';
        $info['tracking_list']= $info['tracking_list']? json_decode($info['tracking_list'],true) : [];
        return $info;
    }
    
}
